package com.example.myapplication.navigation.fragment_login;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.SavedStateHandle;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.myapplication.bean.User;
import com.example.myapplication.databinding.viewmodel.UserViewModel;
import com.example.myapplication.databinding.FragmentLoginBinding;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class LoginFragment extends Fragment {

    FragmentLoginBinding binding;

    public static String LOGIN_SUCCESSFUL = "LOGIN_SUCCESSFUL";

    private UserViewModel userViewModel;
    private SavedStateHandle savedStateHandle;

    public LoginFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentLoginBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        userViewModel = new ViewModelProvider(requireActivity()).get(UserViewModel.class);

        savedStateHandle = Navigation.findNavController(view)
                .getPreviousBackStackEntry()
                .getSavedStateHandle();

        savedStateHandle.set(LOGIN_SUCCESSFUL, false);

        binding.btnOk.setOnClickListener(v -> {
            User user = new User(32, "龙哥来了");
            userViewModel.mUserLiveData.setValue(user);
            savedStateHandle.set(LOGIN_SUCCESSFUL, true);
            Navigation.findNavController(v).popBackStack();
        });

        binding.btnCancel.setOnClickListener(v -> Navigation.findNavController(v).popBackStack());
    }
}
